import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import Ridge
from sklearn.datasets import load_boston
from sklearn.metrics import mean_squared_error

# 1. 数据加载和处理
# 使用波士顿房价数据集
data = load_boston()
X = data.data
y = data.target

# 2. 数据集划分：70%训练集，30%测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

# 3. 建立岭回归模型，设置正则化参数alpha
ridge = Ridge(alpha=1.0)  # alpha 控制正则化强度
ridge.fit(X_train, y_train)

# 4. 预测
y_pred = ridge.predict(X_test)

# 5. 评估模型性能：均方误差（MSE）
mse = mean_squared_error(y_test, y_pred)
print(f"Mean Squared Error: {mse:.2f}")

# 6. 可视化回归结果（预测值与实际值的对比）
plt.scatter(y_test, y_pred)
plt.plot([y.min(), y.max()], [y.min(), y.max()], '--r', label="Ideal Fit")
plt.xlabel("Actual Values")
plt.ylabel("Predicted Values")
plt.title("Ridge Regression: Actual vs Predicted")
plt.legend()
plt.show()
